<template>
  <common-edit-dialog
    :title="title ? '编辑告警码' : '新增告警码'"
    :visible="visible"
    @cancel="cancel"
    @submit="submitForm"
    :button-loading="buttonLoading"
  >
    <el-form
      label-width="90px"
      :rules="rules"
      ref="form"
      :model="form"
      @submit.native.prevent
    >
      <el-row :gutter="24">
        <el-col :span="24" class="col">
          <el-row style="width: 100%">
            <el-form-item
              label="告警码"
              prop="manuCode"
              style="margin-bottom: 0"
            >
              <el-col :span="8">
                <el-form-item prop="manuCode" class="manuCode">
                  <el-select
                    clearable
                    :disabled="isDisabled"
                    placeholder="厂商编码"
                    data-test="alarm-code-input-manuCode"
                    filterable
                    default-first-option
                    v-model="form.manuCode"
                    @change="manCode"
                  >
                    <el-option
                      v-for="item in isAlarmCodeManage
                        ? manuCodeList
                        : manuCodeListSelf"
                      :label="item.manuCode"
                      :value="item.manuCode"
                      :key="item.id"
                      data-test="alarm-code-manuCode-li-option"
                    >
                      <CommonOptionSpan
                        :date="{
                          left: item.manuCode,
                          right: item.corporateName,
                        }"
                      ></CommonOptionSpan>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="systemCode" class="code">
                  <el-select
                    data-test="alarm-code-input-systemCode"
                    :disabled="isDisabled"
                    clearable
                    filterable
                    placeholder="系统编码"
                    default-first-option
                    v-model="form.systemCode"
                  >
                    <el-option
                      data-test="alarm-code-systemCode-li-option"
                      v-for="item in systemCodeList"
                      :label="item.name"
                      :value="item.name"
                      :key="item.id"
                    >
                      <CommonOptionSpan
                        :date="{
                          left: item.name,
                          right: item.alarmSysName,
                        }"
                      ></CommonOptionSpan>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="alarmCodeNum" class="code">
                  <common-input
                    data-test="alarm-code-input-alarmCodeNum"
                    :disabled="isDisabled"
                    v-model="form.alarmCodeNum"
                    placeholder="0-F,4位数"
                    :maxlength="4"
                  />
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-form-item label="告警等级" prop="alarmLevel">
            <el-select
              v-model="form.alarmLevel"
              style="width: 100%"
              clearable
              data-test="alarm-code-input-alarmLevel"
            >
              <el-option
                data-test="alarm-code-alarmLevel-li-option"
                v-for="(item, index) in isAlarmCodeManage
                  ? alarmLevelOption
                  : alarmLevelList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="告警类型" prop="alarmType">
            <el-select
              data-test="alarm-code-input-alarmType"
              clearable
              placeholder="请选择"
              style="width: 100%"
              :disabled="isDisabled"
              v-model="form.alarmType"
              @change="alarmTypeChange(form.alarmType)"
            >
              <el-option
                data-test="alarm-code-alarmType-li-option"
                v-for="item in isAlarmCodeManage
                  ? alarmTypeOption
                  : alarmTypeOptionSelf"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--
        <el-col :span="12">
          <el-form-item label="告警子类型" prop="alarmBusiness">
            <el-select
              data-test="alarm-code-input-alarmBusiness"
              v-model="form.alarmBusiness"
              style="width: 100%"
              clearable
            >
              <el-option
                data-test="alarm-code-alarmBusiness-li-option"
                v-for="item in sysAlarmBusinessList"
                :key="item.id"
                :label="item.alarmBusiness"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12" class="periodCountCol">
          <el-form-item label="告警周期 " prop="alarmPeriodType">
            <el-select
              data-test="alarm-code-input-alarmPeriodType"
              clearable
              v-model="form.alarmPeriodType"
              style="width: 100%"
              @change="alarmPeriodCountChange(form.alarmPeriodType)"
            >
              <el-option
                label="无"
                :value="'0'"
                data-test="alarm-code-alarmPeriodType-li-option0"
              ></el-option>
              <el-option
                label="天"
                :value="'1'"
                data-test="alarm-code-alarmPeriodType-li-option1"
              ></el-option>
              <el-option
                label="小时"
                :value="'2'"
                data-test="alarm-code-alarmPeriodType-li-option2"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="alarmPeriodCount" class="periodCount">
            <common-input-number
              data-test="alarm-code-input-periodCount"
              style="width: 100%"
              :disabled="form.alarmPeriodType === '0' ? true : false"
              v-model="form.alarmPeriodCount"
              placeholder="请输入"
            ></common-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="通知方式"
            prop="noticeTypeList"
            :rules="form.noticeUsers.length ? rules.noticeTypeList : []"
          >
            <el-select
              data-test="alarm-code-input-noticeTypeList"
              :multiple="true"
              v-model="form.noticeTypeList"
              placeholder="请选择"
              clearable
              @change="changeNoticeType"
            >
              <el-option
                v-for="item in noticeTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="通知人"
            prop="noticeUsers"
            :rules="form.noticeTypeList.length ? rules.noticeUsers : []"
          >
            <choose-dialog
              :id="form.id"
              @getSelectData="getSelectData"
            ></choose-dialog>

            <!--                        <el-select-->
            <!--                          :multiple="true"-->
            <!--                          v-model="form.noticeUsers"-->
            <!--                          placeholder="请选择"-->
            <!--                          clearable-->
            <!--                          collapse-tags-->
            <!--                          :filterable="true"-->
            <!--                          :popper-append-to-body="false"-->
            <!--                        >-->
            <!--                          <el-option-->
            <!--                            v-for="item in userList"-->
            <!--                            :label="item.userName"-->
            <!--                            :key="item.userId"-->
            <!--                            :value="item.userId"-->
            <!--                            :disabled="item.freeze !== 'N'"-->
            <!--                          >-->
            <!--                          </el-option>-->
            <!--                        </el-select>-->
          </el-form-item>
        </el-col>

        <!-- <el-col :span="24">
          <el-form-item
            label="工单流程"
            :style="warningOpen ? 'margin-bottom: 0' : 'margin-bottom:18px'"
          >
            <el-select
              v-model="businessPlateCheckedId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="(item, index) in businessPlateList"
                :key="index"
                :label="item.name"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <div v-show="warningOpen" class="warning">
            <span class="el-icon-warning"
              >工单服务异常，工单流程数据暂时无法显示</span
            >
          </div>
        </el-col> -->

        <el-col :span="24">
          <!-- <el-form-item label="备注" prop="remark" show-overflow-tooltip>
            <common-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 8 }"
              v-model="form.remark"
              placeholder="请输入"
            />
          </el-form-item> -->
          <el-form-item label="告警模板" prop="alarmTemplate">
            <div style="width: 100%; height: 120px">
              <code-editor
                data-test="alarm-code-input-alarmTemplate"
                key="alarm-template-editor"
                v-model="form.alarmTemplate"
                :variable="variable"
                placeholder="变量示例: &{userName}; 只支持英文状态的&符号"
              ></code-editor>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </common-edit-dialog>
</template>
<script>
import { sortRule } from "@/utils/formRules";
import { getVendorsList } from "@/api/system/vendors";
import { mapState } from "vuex";
import CodeEditor from "@/components/CodeEditor";
import {
  alarmCodeGetAlarmType,
  businessList,
  alarmProductCodes,
} from "@/api/system/alarmCode";
import ChooseDialog from "../chooseDialog";
import { getAlarmParam } from "@/api/system";

export default {
  name: "CommonAlarmDialog",
  components: { ChooseDialog, CodeEditor },
  props: {
    title: {
      type: Boolean,
    },
    visible: {
      type: Boolean,
    },
    width: {
      type: String,
    },
    alarmLevelOption: {
      type: Array,
      default: () => [],
    },
    alarmTypeOption: {
      type: Array,
      default: () => [],
    },
    manuCodeList: {
      type: Array,
      default: () => [],
    },
    isAlarmCodeManage: {
      type: Boolean,
      default: false,
    },
    buttonLoading: {
      type: Boolean,
      default: false,
    },
    noticeTypeList: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    ...mapState("rule", ["alarmLevelList"]),
  },
  data() {
    const checkPath = (rule, value, callback) => {
      const path = new RegExp("^[0-9A-F]{4}$");
      if (path.test(value)) {
        callback();
      } else {
        callback(new Error("请输入( 0-F )4位数"));
      }
    };
    const checkCount = (rule, value, callback) => {
      if (this.form.alarmPeriodType === "0") {
        callback();
      } else {
        if (!value) {
          callback(new Error("请输入告警周期"));
        } else if (value && value < 1) {
          callback(new Error("告警周期不允许小于0"));
        } else {
          callback();
        }
      }
    };

    return {
      businessPlateCheckedId: "",
      warningOpen: false,
      businessPlateList: [],
      userList: [],
      sysAlarmBusinessList: [],
      alarmTypeOptionSelf: [],
      // alarmLevelOptionSelf: [],
      systemCodeList: [],
      manuCodeListSelf: [],
      isDisabled: false,
      form: {
        alarmBusiness: "",
        manuCode: "",
        alarmCodeNum: "",
        systemCode: "",
        id: "",
        alarmCode: "", //告警码
        alarmContent: "", //告警内容
        alarmLevel: "", //告警等级
        alarmType: "", //告警类型
        noticeContent: "",
        alarmTemplate: "", //备注
        noticeTypeList: [], // 通知方式
        noticeUsers: [],
        alarmPeriodType: "0",
        alarmPeriodCount: 0,
      },
      rules: {
        alarmBusiness: [
          {
            required: true,
            message: "请选择告警子类型",
            trigger: "blur",
          },
        ],
        noticeTypeList: [
          { required: true, message: "请选择通知方式", trigger: "blur" },
        ],
        noticeUsers: [
          { required: true, message: "请选择通知人", trigger: "blur" },
        ],
        alarmPeriodCount: [
          { min: 1, required: true, validator: checkCount, trigger: "blur" },
        ],
        manuCode: [
          {
            required: true,
            message: "请选择厂商编码",
            trigger: "blur",
          },
        ],
        systemCode: [
          {
            required: true,
            message: "请选择系统编码",
            trigger: "blur",
          },
        ],
        alarmCodeNum: [
          {
            required: true,
            message: "请输入告警码",
            trigger: "blur",
          },
          { required: true, validator: checkPath, trigger: "blur" },
        ],
        alarmContent: [
          {
            required: true,
            message: "请输入告警内容",
            trigger: "blur",
          },
        ],
        alarmLevel: [
          {
            required: true,
            message: "请选择告警等级",
            trigger: "blur",
          },
        ],
        alarmType: [
          {
            required: true,
            message: "请选择告警类型",
            trigger: "blur",
          },
        ],
        alarmTemplate: [
          { required: true, message: "请输入告警模板", trigger: "blur" },
        ],

        orderNum: sortRule,
      },
      defaultContent: [
        {
          noticeType: "workOrder", // 工单: workOrder 系统消息: message 邮件: email 短信: sms
          checked: 0, // 0: 选中 1: 未选中
          account: "", // deploymentId,name,key
        },
        { noticeType: "message", checked: 0, account: "" },
        { noticeType: "email", checked: 0, account: "" },
        { noticeType: "sms", checked: 0, account: "" },
        { noticeType: "gsWorkOrder", checked: 0, account: "" },
      ],
      variable: [],
    };
  },

  methods: {
    changeNoticeType(val) {
      // if (val && val.length > 0) {
      //   this.rules["noticeTypeList"][0].required = true;
      //   this.rules["noticeUsers"][0].required = true;
      // } else {
      //   this.rules["noticeTypeList"][0].required = false;
      //   this.rules["noticeUsers"][0].required = false;
      // }
    },
    getAlarmParam() {
      getAlarmParam().then((res) => {
        if (res?.code === 200) {
          this.variable = res.data.reduce((r, c) => {
            r.push({
              label: c.name,
              value: c.id,
            });
            return r;
          }, []);
        } else {
          this.variable = [];
        }
      });
    },

    cancel() {
      this.$emit("cancel");
      this.form = this.$options.data().form;
    },

    submitForm() {
      this.form.alarmCode =
        this.form.manuCode + this.form.systemCode + this.form.alarmCodeNum;
      let noticeContent = this.defaultContent.reduce((r, c) => {
        if (c.noticeType === "workOrder") {
          if (this.businessPlateCheckedId) {
            let obj = this.businessPlateList.find(
              (item) => item.key === this.businessPlateCheckedId
            );

            r.push({
              noticeType: c.noticeType,
              checked: 0,
              account: `${obj.deploymentId},${obj.name},${obj.key}`,
            });
          } else {
            if (this.businessPlateList.length == 0) {
              r.push(this.account || "");
            } else {
              r.push({
                noticeType: c.noticeType,
                checked: 1,
                account: "",
              });
            }
          }
        } else {
          let checked = this.form.noticeTypeList.includes(c.noticeType);
          r.push({
            noticeType: c.noticeType,
            checked: checked ? 0 : 1,
            account: checked
              ? this.form.noticeUsers && this.form.noticeUsers.join(",")
              : "",
          });
        }

        return r;
      }, []);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let form = {
            ...this.form,
            alarmNotice: JSON.stringify(noticeContent),
          };

          if (!this.isAlarmCodeManage) {
            form.alarmTypeCN = this.alarmTypeOptionSelf.find(
              (item) => item.id === this.form.alarmType
            )?.name;

            form.alarmBusinessName = this.sysAlarmBusinessList.find(
              (item) => +item.id === +this.form.alarmBusiness
            )?.alarmBusiness;
          }
          this.$emit("submit", form);
        }
      });
    },
    alarmPeriodCountChange(row) {
      if (row === "0") {
        this.form.alarmPeriodCount = 0;
      }
    },
    alarmTypeChange(row, alarmBusiness, flag) {
      businessList({ alarmType: row }).then((res) => {
        if (res && res.code === 200) {
          this.sysAlarmBusinessList = res.rows;
          if (
            this.sysAlarmBusinessList &&
            this.sysAlarmBusinessList.length > 0
          ) {
            if (flag === "isEdit") {
              this.form.alarmBusiness = alarmBusiness;
            } else {
              this.form.alarmBusiness = this.sysAlarmBusinessList[0].id;
            }
          } else {
            this.form.alarmBusiness = "";
          }
        } else {
          this.sysAlarmBusinessList = [];
          this.form.alarmBusiness = "";
        }
      });
    },
    getManuCodeList() {
      getVendorsList().then((res) => {
        this.manuCodeListSelf = res.rows;
      });
    },
    alarmProductCodes(res) {
      alarmProductCodes({ manuCode: res }).then((res) => {
        this.systemCodeList = res.data;
      });
    },
    manCode(res) {
      this.alarmProductCodes(res);
      this.form.systemCode = "";
    },
    // getAlarmLevel() {
    //   alarmCodeGetAlarmLevel().then((res) => {
    //     this.alarmLevelOptionSelf = res.data;
    //     this.$store.commit("rule/SET_ALARM_LEVEL_LIST", res.data || []);
    //   });
    // },
    getAlarmType() {
      alarmCodeGetAlarmType().then((res) => {
        this.alarmTypeOptionSelf = res.data;
        this.$store.commit("rule/SET_ALARM_TYPE_LIST", res.data || []);
      });
    },
    isAdd() {
      if (this.title) {
      } else {
        this.form = this.$options.data().form;
      }
    },
    handleAdd() {
      this.form = this.$options.data().form;
      this.sysAlarmBusinessList = [];
      this.isDisabled = false;
      if (this.businessPlateList.length == 0) {
        this.warningOpen = true;
      } else {
        this.warningOpen = false;
      }
    },

    handleUpdate(row) {
      console.log(row);
      this.isDisabled = true;
      row.alarmPeriodType = row.alarmPeriodType.toString();
      row.alarmPeriodCount = parseInt(row.alarmPeriodCount);
      Reflect.ownKeys(this.form).forEach((k) => (this.form[k] = row[k]));
      // this.form.alarmBusiness = parseInt(row.alarmBusiness);

      this.form.alarmLevel = this.alarmLevelOption.find(
        (item) => item.name === row.alarmLevel
      ).id;
      this.form.alarmType = this.alarmTypeOption.find(
        (item) => item.name === row.alarmType
      ).id;
      this.alarmTypeChange(this.form.alarmType, row.alarmBusiness, "isEdit");
      this.alarmPeriodCountChange(row.alarmPeriodType);
      // this.form.alarmBusiness = this.sysAlarmBusinessList.find(
      //   (item) => item.alarmBusiness === row.alarmBusinessName
      // )?.id;
      this.form.noticeTypeList = [];
      this.form.noticeUsers = [];
      this.form.manuCode = row.alarmCode.slice(0, 4);
      this.form.systemCode = row.alarmCode.slice(4, 6);
      this.form.alarmCodeNum = row.alarmCode.slice(6, 10);
      if (row.alarmNotice) {
        let alarmNotice = JSON.parse(row.alarmNotice);
        alarmNotice.forEach((item) => {
          if (item != null) {
            if (item.noticeType == "workOrder") {
              this.account = item;
              if (
                this.businessPlateList &&
                this.businessPlateList.length == 0
              ) {
                this.businessPlateCheckedId = "";
                this.warningOpen = true;
              } else {
                let account = item.account && item.account.split(",");
                this.businessPlateCheckedId = account[2];
              }
            } else {
              if (item.checked === 0) {
                this.form.noticeUsers = item.account
                  ? item.account.split(",")
                  : "";
                this.form.noticeTypeList.push(item.noticeType);
              }
            }
          }
        });
      }
    },

    /**
     * 获取选择列表
     */
    getSelectData(data) {
      this.form.noticeUsers = [];
      data.forEach((item) => {
        this.form.noticeUsers.push(item.userId);
      });
    },
  },
  created() {
    this.getAlarmParam();
    if (!this.isAlarmCodeManage) {
      this.getManuCodeList();
      // this.getAlarmLevel();
      this.getAlarmType();
    }
  },
};
</script>

<style scoped lang="scss">
.col {
  display: flex;

  .manuCode {
    ::v-deep .el-form-item__content {
      margin-left: 0px !important;
    }
  }

  .code {
    ::v-deep .el-form-item__content {
      margin-left: 8px !important;
    }
  }
}

.periodCountCol {
  display: flex;

  .periodCount {
    ::v-deep .el-form-item__content {
      margin-left: 8px !important;
    }
  }
}

.warning {
  margin-bottom: 4px;
}

.el-icon-warning {
  color: #f56c6c;
  margin-left: 80px;
  font-size: 12px;
  line-height: 16px;
}
</style>
